import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Popconfirm,
  Tag,
  Typography,
  Row,
  Col,
  Tooltip,
  Switch
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  BellOutlined
} from '@ant-design/icons';
import { notificationAPI } from '../utils/api';
import { useAuth } from '../context/AuthContext';
import { usePermissions, PERMISSIONS } from '../utils/permissions';
import moment from 'moment';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { confirm } = Modal;

const NotificationManagement = () => {
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingNotification, setEditingNotification] = useState(null);
  const [form] = Form.useForm();
  const { user } = useAuth();
  const { hasPermission } = usePermissions(user);

  // 检查权限
  const hasAccess = hasPermission(PERMISSIONS.NOTIFICATION_MANAGE);

  // 获取通知列表
  const fetchNotifications = async () => {
    setLoading(true);
    try {
      const response = await notificationAPI.getAllNotifications();
      setNotifications(response.notifications || []);
    } catch (error) {
      message.error('获取通知列表失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 创建或更新通知
  const handleSubmit = async (values) => {
    try {
      const notificationData = {
        ...values,
        expires_at: values.expires_at ? values.expires_at.toISOString() : null,
        target_users: values.target_users || [],
        is_active: values.is_active !== undefined ? values.is_active : true
      };

      if (editingNotification) {
        await notificationAPI.updateNotification(editingNotification.id, notificationData);
        message.success('通知更新成功');
      } else {
        await notificationAPI.createNotification(notificationData);
        message.success('通知创建成功');
      }

      setModalVisible(false);
      setEditingNotification(null);
      form.resetFields();
      fetchNotifications();
    } catch (error) {
      message.error(editingNotification ? '更新失败' : '创建失败');
      console.error(error);
    }
  };

  // 删除通知
  const handleDelete = async (id) => {
    try {
      await notificationAPI.deleteNotification(id);
      message.success('删除成功');
      fetchNotifications();
    } catch (error) {
      message.error('删除失败');
      console.error(error);
    }
  };

  // 批量删除
  const handleBatchDelete = async (selectedRowKeys) => {
    try {
      await notificationAPI.batchDeleteNotifications(selectedRowKeys);
      message.success('批量删除成功');
      fetchNotifications();
    } catch (error) {
      message.error('批量删除失败');
      console.error(error);
    }
  };

  // 打开编辑模态框
  const openEditModal = (notification) => {
    setEditingNotification(notification);
    form.setFieldsValue({
      ...notification,
      expires_at: notification.expires_at ? moment(notification.expires_at) : null
    });
    setModalVisible(true);
  };

  // 打开创建模态框
  const openCreateModal = () => {
    setEditingNotification(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setModalVisible(false);
    setEditingNotification(null);
    form.resetFields();
  };

  // 表格列定义
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text, record) => (
        <div>
          <Text strong={!record.is_active}>{text}</Text>
          {!record.is_active && <Tag color="default">已停用</Tag>}
        </div>
      )
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      width: 300,
      render: (text) => (
        <Tooltip title={text}>
          <Text ellipsis={{ tooltip: text }}>{text}</Text>
        </Tooltip>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => {
        const typeConfig = {
          info: { color: 'blue', text: '信息' },
          warning: { color: 'orange', text: '警告' },
          error: { color: 'red', text: '错误' },
          success: { color: 'green', text: '成功' }
        };
        const config = typeConfig[type] || { color: 'default', text: type };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 100,
      render: (priority) => {
        const priorityConfig = {
          low: { color: 'default', text: '低' },
          medium: { color: 'blue', text: '中' },
          high: { color: 'red', text: '高' }
        };
        const config = priorityConfig[priority] || { color: 'default', text: priority };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '目标用户',
      dataIndex: 'target_users',
      key: 'target_users',
      width: 150,
      render: (users) => {
        if (!users || users.length === 0) {
          return <Tag color="blue">所有用户</Tag>;
        }
        return (
          <Tooltip title={users.join(', ')}>
            <Text ellipsis={{ tooltip: users.join(', ') }}>
              {users.length > 2 ? `${users.slice(0, 2).join(', ')}...` : users.join(', ')}
            </Text>
          </Tooltip>
        );
      }
    },
    {
      title: '创建者',
      dataIndex: 'created_by',
      key: 'created_by',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date) => moment(date).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '过期时间',
      dataIndex: 'expires_at',
      key: 'expires_at',
      width: 150,
      render: (date) => date ? moment(date).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (active) => (
        <Tag color={active ? 'success' : 'default'}>
          {active ? '激活' : '停用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个通知吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 初始化
  useEffect(() => {
    fetchNotifications();
  }, []);

  // 如果没有权限，显示权限不足页面
  if (!hasAccess) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <ExclamationCircleOutlined style={{ fontSize: '48px', color: '#faad14' }} />
        <Title level={3}>权限不足</Title>
        <Text>您没有权限访问通知管理功能</Text>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              <BellOutlined style={{ marginRight: '8px' }} />
              通知管理
            </Title>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={openCreateModal}
            >
              新建通知
            </Button>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={notifications}
          loading={loading}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑通知模态框 */}
      <Modal
        title={editingNotification ? '编辑通知' : '新建通知'}
        open={modalVisible}
        onCancel={closeModal}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            type: 'info',
            priority: 'medium',
            is_active: true
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="通知标题"
                rules={[{ required: true, message: '请输入通知标题' }]}
              >
                <Input placeholder="请输入通知标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="通知类型"
                rules={[{ required: true, message: '请选择通知类型' }]}
              >
                <Select placeholder="请选择通知类型">
                  <Option value="info">信息</Option>
                  <Option value="warning">警告</Option>
                  <Option value="error">错误</Option>
                  <Option value="success">成功</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="请选择优先级">
                  <Option value="low">低</Option>
                  <Option value="medium">中</Option>
                  <Option value="high">高</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="expires_at"
                label="过期时间"
              >
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm"
                  placeholder="请选择过期时间"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="content"
            label="通知内容"
            rules={[{ required: true, message: '请输入通知内容' }]}
          >
            <TextArea
              rows={4}
              placeholder="请输入通知内容"
              maxLength={500}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="target_users"
            label="目标用户"
          >
            <Select
              mode="tags"
              placeholder="留空表示所有用户，或选择特定用户"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="激活" unCheckedChildren="停用" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={closeModal}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingNotification ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default NotificationManagement;
